<template>
  <div>

    <!-- 查询条件表单 -->
    <div class="query-form">
      <a-form ref="formRef" :model="queryForm" label-align="left" auto-label-width>
        <a-row justify="start" :gutter="16">
          <a-col :span="6">
            <a-form-item field="name" :label="$t('code.columns.name')">
              <a-input v-model="queryForm.name"
                :placeholder="$t('common.inputPlaceholder') + $t('code.columns.name')" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="code" :label="$t('code.columns.code')">
              <a-input v-model="queryForm.code"
                :placeholder="$t('common.inputPlaceholder') + $t('code.columns.code')" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div>
        <!-- 查询按钮 -->
        <a-button-group>
          <a-button type="primary" @click="search">{{ t('common.search') }}</a-button>
          <a-button @click="clear">{{ t('common.clear') }}</a-button>
        </a-button-group>
      </div>
    </div>

    <!-- 数据表格 -->
    <a-table ref="tableRef" :columns="columns" :data="tableData" :pagination="false" stripe table-layout-fixed
      row-key="id" @select="onSelect" :selected-keys="selectedKeys" :row-selection="rowSelection">
      <template #optional="{ record }">
        <a-button @click="openAddChildModal(record)" type="text" :title="$t('common.add')">
          <template #icon>
            <icon-plus />
          </template>
        </a-button>
        <a-button type="text" size="small" @click="openEditModal(record)" :title="$t('common.edit')">
          <template #icon>
            <icon-edit />
          </template>
        </a-button>
        <a-popconfirm :content="$t('common.deleteTip')" @ok="remove(record)">
          <a-button type="text" :title="$t('common.remove')" status="danger">
            <template #icon>
              <icon-delete />
            </template>
          </a-button>
        </a-popconfirm>
      </template>
      <template #footer>
        <div class="table-footer">
          <a-button-group>
            <a-button type="primary" @click="openEditModal()">
              <template #icon>
                <icon-plus />
              </template>
              {{ t('common.add') }}</a-button>
            <!-- <a-button @click="clear">
                          <template #icon>
                              <icon-upload />
                          </template>
                          {{ t('common.importFile') }}</a-button>
                      <a-button @click="clear">
                          <template #icon>
                              <icon-download />
                          </template>
                          {{ t('common.exportFile') }}</a-button> -->

            <a-popconfirm :content="$t('common.deleteTip')" @ok="remove">
              <a-button status="danger" :disabled="selectedKeys.length === 0">
                <template #icon>
                  <icon-delete />
                </template>
                {{ t('common.batchDelete') }}</a-button>
            </a-popconfirm>
          </a-button-group>
        </div>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal v-model:visible="modalVisiable" :on-before-ok="handleOk" @cancel="closeEditModal" @close="closeEditModal">
      <template #title>
        {{ dataFormTitle }}
      </template>
      <a-form :model="dataForm" ref="dataFormRef" :rules="dataFormRules">
        <a-form-item field="parentId" :label="$t('code.columns.pid')">
          <a-tree-select v-model="dataForm.pid" allow-clear :data="treeOption" :field-names="{ icon: () => { } }"
            :placeholder="$t('common.selectPlaceholder') + $t('code.columns.pid')">
          </a-tree-select>
        </a-form-item>
        <a-form-item field="name" :label="$t('code.columns.name')">
          <a-input v-model="dataForm.name" :placeholder="$t('common.inputPlaceholder') + $t('code.columns.name')" />
        </a-form-item>
        <a-form-item field="code" :label="$t('code.columns.code')">
          <a-input v-model="dataForm.code" :placeholder="$t('common.inputPlaceholder') + $t('code.columns.code')" />
        </a-form-item>
        <a-form-item field="comments" :label="$t('code.columns.comments')">
          <a-input v-model="dataForm.comments"
            :placeholder="$t('common.inputPlaceholder') + $t('code.columns.comments')" />
        </a-form-item>
      </a-form>
    </a-modal>


  </div>
</template>
<script setup>
import { list, show, logicalDel, save } from '@/api/code.js'
import { options } from '@/api/dict';
import { onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Message } from '@arco-design/web-vue'
const { t } = useI18n()

// 表格字段
const columns = [{
  title: t('code.columns.name'),
  dataIndex: 'name',
}, {
  title: t('code.columns.code'),
  dataIndex: 'code',
},
{
  title: t('code.columns.comments'),
  dataIndex: 'comments',
},
{
  title: t('user.columns.createTime'),
  dataIndex: 'createTime',
  width: 200
},
{
  title: t('user.columns.updateTime'),
  dataIndex: 'updateTime',
  width: 200
},
{
  title: t('common.optional'),
  fixed: 'right',
  slotName: 'optional',
  width: 150
}];
// 表格多选
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
const selectedKeys = ref([])
const onSelect = (rowKeys) => {
  selectedKeys.value = rowKeys
}
// 表格数据
const tableData = ref()
const tableRef = ref()
const treeOption = ref([])

// 查询表单
const formRef = ref()
// 查询表单条件
const queryForm = reactive({
  name: '',
  value: '',
  status: null,
  page: {
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: true
  }
})
// 查询表格数据
const search = () => {
  let searchParams = []
  if (queryForm.name) {
    searchParams.push(
      {
        "column": "name",
        "operator": "LIKE",
        "value": queryForm.name,
      }
    )
  }
  if (queryForm.value) {
    searchParams.push(
      {
        "column": "value",
        "operator": "LIKE",
        "value": queryForm.value,
      }
    )
  }
  let params = {
    "searchParams": searchParams
  }
  list(params).then(res => {
    if (res.code === 200) {
      tableData.value = res.data
      queryForm.page.current = res.data.current
      queryForm.page.pageSize = res.data.size
      queryForm.page.total = res.data.total
    } else {
      Message.error(res.message)
    }
  })
}
// 清空查询条件
const clear = () => {
  formRef.value.resetFields()
}

// 加载字典信息
const statusOption = ref([])
const loadDict = (dictType) => {
  options({ dictType: dictType }).then(res => {
    if (res.code === 200) {
      statusOption.value = res.data
    }
  })
}


// 新增/编辑弹窗
let dataForm = ref({})
const dataFormRef = ref()
const dataFormTitle = ref('')
const modalVisiable = ref(false)
const dataFormRules = {
  name: [
    {
      required: true,
      message: t('common.inputPlaceholder') + t('code.columns.name'),
    },
  ],
  code: [
    {
      required: true,
      message: t('common.inputPlaceholder') + t('code.columns.code'),
    }
  ],
}

const loadTreeOption = () => {
  list({}).then(res => {
    treeOption.value = transferOption(res.data)
  })
}

const transferOption = (codes) => {
  let treeOption = []
  codes.forEach(element => {
    let data = {
      key: element.id,
      title: element.name,
      children: []
    }
    if (element.children && element.children.length > 0) {
      data.children = transferOption(element.children)
    }
    treeOption.push(data)
  });
  return treeOption
}

const openAddChildModal = async (item) => {
  await loadTreeOption()
  dataForm.value.pid = item.id
  dataFormTitle.value = t('common.add')
  modalVisiable.value = true
}


// 打开新增/编辑弹窗
const openEditModal = (item) => {
  if (item) {
    show({ id: item.id }).then(res => {
      if (res.code === 200) {
        dataForm.value = res.data
        modalVisiable.value = true
      } else {
        Message.error(res.message)
      }
    })
    dataFormTitle.value = t('common.edit')
  } else {
    dataFormTitle.value = t('common.add')
    modalVisiable.value = true
  }

}

const handleOk = async () => {
  return await new Promise((resolve) => {
    dataFormRef.value.validate((values) => {
      if (!values) {
        // 验证通过
        save(dataForm.value).then(res => {
          if (res.code === 200) {
            Message.success(t('common.operateSuccess'))
            modalVisiable.value = false
            search()
            resolve(true)
          } else {
            Message.success(res.message)
            resolve(false)
          }
        })
      } else {
        resolve(false)
      }
    })
  })
}
// 关闭新增/编辑弹窗
const closeEditModal = () => {
  dataFormRef.value.resetFields()
  dataForm.value = {}
  modalVisiable.value = false
}

const remove = (item) => {
  let deleteIds = []
  if (item) {
    // 单个删除
    deleteIds.push(item.id)
  } else {
    deleteIds = [...selectedKeys.value]
  }
  if (deleteIds.length === 0) {
    Message.warning(t('common.chooseDeleteItem'))
    return
  }
  logicalDel({ ids: deleteIds }).then(res => {
    if (res.code === 200) {
      Message.success(t('common.operateSuccess'))
      search()
    } else {
      Message.error(res.message)
    }
  })
}

onMounted(() => {
  loadDict('status')
  search()
})
</script>
<style lang="less"></style>